<?php
/**
 * Controller Class: Account
 * This class handles every users account within the system.
 * It provides actions for logging in, logging out and registering with the system.
 * @author ovo
 *
 */
class Account_UsersController extends Zend_Controller_Action
{

	protected $_redirector = null;
	
    public function init()
    {
    	
    }

    public function indexAction()
    {
    }

    /**
     * Function: Login
     * This function allows the user to login to the application.
     */
    public function loginAction()
    { 	
				
	$this->view->headTitle('Login ', 'PREPEND'); 
	$this->view->message =  implode(" ", $this->_helper->flashMessenger->getMessages());
        /* Initialize action controller here */
		$request = $this->getRequest();
		$form = new Account_Form_Login();
     
	if($request->isPost()) {
			if ($form->isValid($this->getRequest()->getPost()))	{
				
				$authAdapter = $this->getAuthAdapter();
				$username = $form->getValue('username');
				$password = $form->getValue('password');
				
				$authAdapter->setIdentity($username)
							->setCredentialTreatment('md5(?)')
							->setCredential($password);
							
				//Getting an instance of Zend_Auth
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				
				if ($result->isValid()){
				
					//Get row object of identity related to this user
					$identity = $authAdapter->getResultRowObject();
					//Get session wide storage
					if ($identity->status == "active"){
					
					$authStorage = $auth->getStorage();
					$authStorage->write($identity);					
					$forward = $this->_request->getPost('return');
					//Are we in the home page
					$home = 'account/users/login';
					$pos = strpos($forward, $home);
					if ($pos === false ){
					$this->view->errorMessage=$forward;	
      				// $this->_redirector = $this->_helper->getHelper('Redirector');
      				 //$this->_redirector->setUseAbsoluteUri($forward);
       				return $this->_redirect($forward);
					}
					else
					return $this->_redirect('account/index/index');
					
					}else {
						
						$this->view->errorMessage = "You haven't activated your account!";
					}
       				//$this->_forward($forward);
				} else {
					
					$this->view->errorMessage = "Username or Password invalid";
						}
			}		
    	
}
//Send the form to the view
$this->view->form = $form ;

	}

	
	/**
	 * This action enables a user recover their
	 * password
	 */
	public function recoverAction() {
		$reset = new Account_Model_Users();
		$this->view->title = "Recover your account details";
		$this->view->headTitle($this->view->title, 'PREPEND');
		$form = new Account_Form_Recover();
		$this->view->form = $form;
		if ($this->getRequest()->isPost()){
			$formData = $this->getRequest()->getPost();
		 if ($form->isValid($formData)){
		 	$email = $form->getValue('email');
		 	$val = $reset->checkEmail($email);
		 	//print_r($val);
		 	$count = $val[0]['val'];
		 	if ($count < 1){
		 		$this->view->message = "Your email wasn't found in our databases";
		 	}else{
		 		
		 		$details = $reset->sendUserPassword($email);
		 		$username = $details[0];
		 		$password = $details[1];
		 		$this->sendTo($email, $username, $password);
		 		$this->view->message = "An email has been sent to your account. Please check it for your new username and password";
		 	}
		 	
		 }
		}
		
	}
/**
 * Function: registerAction
 * Params: none
 * This function allows a user to register with the system. 
 */
    public function registerAction()
    {
	    $this->view->title = "Register a new User ";
		$this->view->headTitle($this->view->title, 'PREPEND');
		$form = new Account_Form_Register();
		//$form->submit->setLabel('Register');
		$this->view->form = $form;
		if ($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
		if ($form->isValid($formData)) {
			//$fname = $form->getValue('fname');
			//$lname = $form->getValue('lname');
			$email = $form->getValue('email');
			$school = $form->getValue('school');
			$uname = $form->getValue('username');
			$password = $form->getValue('password');
			
			$users = new Account_Model_Users();
			$users->addUser(/*$fname, $lname,*/$email, $school, $uname, $password);
			$lid = $users->returnlastid();
			$this->_redirect("account/users/thanks/email/$email/id/$lid");
		} else {
						$form->populate($formData);
				}
}
}
    

/**
 * Function: Logout
 * This function logs the user out of the system 
 * by clearing the identity
 */
public function logoutAction() {
	//$this->_helper->layout->disableLayout();
	Zend_Auth::getInstance()->clearIdentity();
	$this->_redirect('/');
}

/**
 * Function: viewProfile
 * This function allows a user view the details of their account.
 */
public function viewprofileAction(){
	
	$userid = $this->_getParam('id');
	$this->view->headTitle("My Profile", 'PREPEND');
	$model = new Account_Model_Users();
	$user = $model->fetchAll("id = ".$userid);
	$this->view->user = $user->toArray();
	//print_r($user);
}
/**
 * Function: editAction
 * This function is used for editing a particular user's records
 */
public function editAction () {
    	$this->view->headTitle("Edit my Profile", 'PREPEND');
		$form = new Account_Form_editProfile();
		$this->view->form = $form;
		if ($this->getRequest()->isPost()) {
				$formData = $this->getRequest()->getPost();
				if ($form->isValid($formData)) {
				$id =$this->_getParam('id');
				$email = $form->getValue('email');
				$school = $form->getValue('school');
				$username = $form->getValue('username');
				$password = $form->getValue('password');
				$userdata = new Account_Model_Users();
				$userdata->editAccount($id,$email, $school, $username,$password);
				$this->_redirect("/account/users/viewprofile/id/$id");
    		}	else {
			$form->populate($formData);
					}
			} else {
				$id = $this->_getParam('id');
			if ($id > 0) {
			$data = new Account_Model_Users();
			$dataset = $data->getUser($id);
			//print_r($dataset);
			$dataset['password'] = "";
			$form->populate($dataset);
			}
}
}
		public function deleteAction($id) {
			
			$user = new Account_Model_Users();
			$user->deleteUser($id);
		}
		/**
		 * Private Function
		 * This gets the authentication adapter for the application
		 */
		private function getAuthAdapter() {
			
			$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter()); 
			$authAdapter->setTableName('users')
			        	->setIdentityColumn('username')
						->setCredentialColumn('password');
		
			return $authAdapter;
		}


		
		/**
		 * Function: thanks
		 * This function sends a registered user an email thanking them for their registration.
		 */
		
		public function thanksAction() {
		$id = $this->_getParam('id');
		$email = $this->_getParam('email');
		// action body
		//Create SMTP connection Object
		$configInfo = array('auth' => 'login',
		'ssl' => 'tls',
		'username' => 'gradeometer000',
		'password' => 'track100',
		'port' => '587');
		$smtpHost = new Zend_Mail_Transport_Smtp('smtp.gmail.com',
		$configInfo);
		//Create Zend_Mail object.
		$MailObj = new Zend_Mail();
		//Initialize parameters.
		$helper = new Zend_View_Helper_Url() ;
		$baseurl = new Zend_View_Helper_ServerUrl();
		$link = $helper->url(array("module"=>"account", "controller"=>"users", "action"=>"activate", "id"=>$id));
		$link = "http://" .$baseurl->getHost().$link;
		$emailMessage = "<br><a href=$link>Click this link to activate your account</a>";
		$fromEmail = "admin@gradeometer.com";
		$fromFullName = "Ovo";
		$to = $email;
		$subject = "Thanks for joining Gradeometer";
		$MailObj->setBodyHtml($emailMessage);
		$MailObj->setFrom($fromEmail, $fromFullName);
		$MailObj->addTo($to);
		$MailObj->setSubject($subject);
		//Send Email using transport protocol.
		try{
				$MailObj->send($smtpHost);
				echo "Email sent successfully";
		}catch(Zend_Mail_Exception $e){
		//Your error message here.
		echo $e->getMessage();
		}
		//Suppress the view.
		}
		

	public function activateAction() {
		
		$id = $this->_getParam('id');
		$filter = new Zend_Filter_StringTrim();
		$model = new Account_Model_Users();
		$model->activateAccount($id);
	}
	
	public function sendTo($email, $user, $password) {
		

		//Create SMTP connection Object
		$configInfo = array('auth' => 'login',
		'ssl' => 'tls',
		'username' => 'gradeometer000',
		'password' => 'track100',
		'port' => '587');
		$smtpHost = new Zend_Mail_Transport_Smtp('smtp.gmail.com',
		$configInfo);
		//Create Zend_Mail object.
		$MailObj = new Zend_Mail();
		//Initialize parameters.
		$helper = new Zend_View_Helper_Url() ;
		$emailMessage = "Your username is : $user<br>Your password has been reseted to: $password";
		$fromEmail = "admin@gradeometer.com";
		$fromFullName = "Gradeometer";
		$to = $email;
		$subject = "Your account has been reset";
		$MailObj->setBodyHtml($emailMessage);
		$MailObj->setFrom($fromEmail, $fromFullName);
		$MailObj->addTo($to);
		$MailObj->setSubject($subject);
		//Send Email using transport protocol.
		try{
				$MailObj->send($smtpHost);
				echo "Email sent successfully";
		}catch(Zend_Mail_Exception $e){
		//Your error message here.
		echo $e->getMessage();
		}
	}
}



